<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2024/1/9
 * Time: 14:28
 */

namespace app\api\controller;

use pay\Ali;
use pay\Wxservicer;
use think\Db;

class Privatebuyorder extends Base
{
    public $user_id;
    public $create_time;
    public $page;

    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status' => 301, 'msg' => $this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }

    /**
     * 提交私人订制套餐购买订单
     * ps_id          套餐ID
     * pay_type       支付方式  1 微信  2 支付宝  3 积分
     * order_number   订单数量
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function CommitBuyPrivateSetMeal(){
        $ps_id = input('ps_id');
        $pay_type = input('pay_type') ? input('pay_type') : 0; // 1 微信    2 支付宝   3 积分
        $order_number = input('order_number');

        if(!$this->user_id) return json(['status' => 0, 'msg' => '请先登录']);

        $setMeal = Db::table('up_private_setmeal')
            ->where('ps_id', $ps_id)
            ->field('ps_vip_price, ps_status, ps_name')
            ->find();
        if(!$setMeal) return json(['status' => 0, 'msg' => '套餐数据错误']);
        if($setMeal['ps_status'] != 1) return json(['status' => 0, 'msg' => '套餐状态异常']);

        $totalPrice = $order_number * $setMeal['ps_vip_price']; // 总金额/积分

        $user = Db::table('up_u_user')
            ->where('user_id', $this->user_id)
            ->field('user_rule, user_bo_balance, user_bo_first_balance, user_bo_huo_balance, user_bo_other_balance')
            ->find();

        if($user['user_rule'] != '1' && $user['user_rule'] != '2'){
            if($pay_type == 3 && $user['user_bo_balance'] < $totalPrice) return json(['status' => 222, 'msg' => '积分不足，请充值']);
            $order_type = 1; // 加盟商
        }else{
            if($pay_type == 3) return json(['status' => 0, 'msg' => '请选择微信或支付宝支付']);
            $order_type = 2; // 普通用户
        }

        $order_no = 'PB_' . date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);

        $order = [
            'order_no' => $order_no,
            'order_user_id' => $this->user_id,
            'order_ps_id' => $ps_id,
            'order_pay_type' => $pay_type,
            'order_number' => $order_number,
            'order_total_price' => $totalPrice,
            'order_type' => $order_type,
            'order_time' => $this->create_time
        ];

        $order_id = Db::table('up_private_buy_order')->insertGetId($order);
        if($order_id){
            return json([
                'status' => 200,
                'msg' => '操作成功',
                'order_id' => $order_id,
                'totalPrice' => $totalPrice,
                'payType' => $pay_type,
                'ps_name' => $setMeal['ps_name']
            ]);
        }else{
            return json(['status' => 0, 'msg' => '操作失败，请稍后重试']);
        }

    }

    /**
     * 支付私人订制购买订单
     * order_id    订单ID
     * pay_type    支付方式  1 微信    2 支付宝   3 积分
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function payBuyPrivateSetMeal(){
        $order_id = input('order_id');
        $pay_type = input('pay_type') ? input('pay_type') : 0; // 1 微信    2 支付宝   3 积分

        $order = Db::table('up_private_buy_order')
            ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
            ->join('up_private_setmeal', 'ps_id = order_ps_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_total_price, user_rule, user_bo_balance, user_bo_first_balance, 
            user_bo_huo_balance, user_bo_other_balance, ps_status, order_status, order_ps_id, 
            order_number, order_no')
            ->find();

        if(!$order) return json(['status' => 0, 'msg' => '订单数据异常']);
        if($order['order_status'] != 1) return json(['status' => 0, 'msg' => '订单状态异常']);
        if($order['ps_status'] != 1) return json(['status' => 0, 'msg' => '购买的套餐状态异常']);

        if($order['user_rule'] != '1' && $order['user_rule'] != '2'){
            if($pay_type == 3 && $order['user_bo_balance'] < $order['order_total_price']) return json(['status' => 222, 'msg' => '积分不足，请充值']);
            $order_type = 1; // 加盟商
        }else{
            if($pay_type == 3) return json(['status' => 0, 'msg' => '请选择微信或支付宝支付']);
            $order_type = 2; // 普通用户
        }

        $mchid = Db::table('up_mchid')->where(['mch_default' => 1, 'mch_status' => 1])->find();
        if(!$mchid) return json(['status' => 0, 'msg' => '暂无可收款账户，请联系客服']);

        $order_status = $pay_type == 3 ? 2 : 1;

        $orderUpdate = [
            'order_id' => $order_id,
            'order_pay_type' => $pay_type,
            'order_type' => $order_type,
            'order_status' => $order_status,
            'order_update_time' => $this->create_time
        ];

        $hasStock = Db::table('up_private_stock')
            ->where(['stock_user_id' => $this->user_id, 'stock_ps_id' => $order['order_ps_id']])
            ->find();

        Db::startTrans();
        try{
            // 更新订单
            Db::table('up_private_buy_order')->update($orderUpdate);

            // 支付
            if($pay_type == 1){
                // 调起微信支付
                $wxConfig = config('wechat_servicer');
                $wxConfig['sub_mchid'] = $mchid['mch_code'];
                $wx = new Wxservicer($wxConfig);
                $return = $wx->WeChatPayReadyServicerV2($order['order_total_price'], $order['order_no'], '购买私人订制套餐礼包');
            }elseif($pay_type == 2){
                // 调起支付宝支付
                $ali = new Ali(config('ali'));
                $return = $ali->getParam($order['order_no'], $order['order_total_price'], '私人订制套餐礼包', '购买私人订制套餐礼包');
            }else{
                // 用户积分
                $update_price = $this->decPrice($order); // 更新用户积分数组
                Db::table('up_u_user')->where('user_id', $this->user_id)->update($update_price);

                // 积分明细
                $this->insertBoInte($this->user_id, 2, '私人订制套餐购买', $order['order_total_price'], $order['user_bo_balance'], $order_id);

                // 如果是积分，增加库存
                if($pay_type == 3){
                    if($hasStock){
                        Db::table('up_private_stock')
                            ->where('stock_id', $hasStock['stock_id'])
                            ->inc('stock_number', $order['order_number'])
                            ->update();
                    }else{
                        Db::table('up_private_stock')
                            ->insert([
                                'stock_user_id' => $this->user_id,
                                'stock_ps_id' => $order['order_ps_id'],
                                'stock_number' => $order['order_number']
                            ]);
                    }
                }
                $return['message'] = '操作成功';
            }

            Db::commit();
            return json(['status' => 200, 'msg' => $return['message'], 'order_id' => $order_id, 'price' => $order['order_total_price']]);
        }catch (\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 私人订制套餐购买订单数量
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyPrivateSetMealOrderStatus(){
        $data = [
            'unPayNumber' => $this->buyPrivateSetMealOrder(2, 1),
            'payNumber' => $this->buyPrivateSetMealOrder(2, 2),
            'cancelOrderNumber' => $this->buyPrivateSetMealOrder(2, 3)
        ];
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 私人订制套餐购买订单列表
     * status     状态  0 全部  1 未支付  2 已支付  3 已取消
     * page       页码
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyPrivateSetMealOrderList(){
        $status = input('status'); // 0 全部  1 未支付  2 已支付  3 已取消
        $list = $this->buyPrivateSetMealOrder(1, $status);
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }

    /**
     * 私人订制套餐购买订单详情
     * order_id    订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyPrivateSetMealOrderDetail(){
        $order_id = input('order_id');

        $data = Db::table('up_private_buy_order')
            ->join('up_private_setmeal', 'ps_id = order_ps_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_id, order_no, order_number, order_total_price, order_status, order_time, 
                ps_name, ps_image, order_pay_type, ps_vip_price, order_ps_id')
            ->find();
        return json(['status' => 200, 'msg' => $data]);
    }

    /**
     * 取消私人订制套餐购买订单
     * order_id     订单ID
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function buyPrivateSetMealOrderCancel(){
        $order_id = input('order_id');

        $order = Db::table('up_private_buy_order')->where('order_id', $order_id)->field('order_status')->find();

        if(!$order) return json(['status' => 0, 'msg' => '订单数据错误']);
        if($order['order_status'] != 1) return json(['status' => 0, 'msg' => '订单状态错误']);

        $res = Db::table('up_private_buy_order')
            ->where('order_id', $order_id)
            ->update([
                'order_status' => 3,
                'order_cancel_time' => $this->create_time
            ]);
        if($res){
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }

    /**
     * 私人订制套餐购买信息
     * @param $type     1 列表  2 统计
     * @param $status   0 全部   1 未支付   2 已支付   3 已取消
     * @return bool|int|\PDOStatement|string|\think\Collection
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function buyPrivateSetMealOrder($type = 1, $status = 0){
        $where['order_user_id'] = $this->user_id;
        if($status != 0) $where['order_status'] = $status;

        $query = Db::table('up_private_buy_order')->where($where);
        if($type == 1){
            $data = $query->join('up_private_setmeal', 'ps_id = order_ps_id', 'LEFT')
                ->field('order_id, order_no, order_number, order_total_price, order_status, order_time, 
                ps_name, ps_image, ps_vip_price, order_ps_id')
                ->order('order_time desc')
                ->page($this->page, 10)
                ->select();
        }else{
            $data = $query->count();
        }
        return $data;
    }


    /**
     * 根据扣款顺序，生成用户剩余积分的更新数组
     * @param $order
     * @return array
     */
    private function decPrice($order){
        $update_price = [
            'user_bo_balance' => $order['user_bo_balance'],
            'user_bo_first_balance' => $order['user_bo_first_balance'],
            'user_bo_huo_balance' => $order['user_bo_huo_balance'],
            'user_bo_other_balance' => $order['user_bo_other_balance']
        ];
        // 扣款顺序，首款>货款
        if($order['order_total_price'] <= $order['user_bo_first_balance']){
            $update_price['user_bo_first_balance'] = $order['user_bo_first_balance'] - $order['order_total_price'];
        }else{
            $update_price['user_bo_first_balance'] = 0;
            $cha1 = $order['order_total_price'] - $order['user_bo_first_balance'];
            if($cha1 <= $order['user_bo_huo_balance']){
                $update_price['user_bo_huo_balance'] = $order['user_bo_huo_balance'] - $cha1;
            }else{
                $update_price['user_bo_huo_balance'] = 0;
                $cha2 = $cha1 - $order['user_bo_huo_balance'];
                if($cha2 <= $order['user_bo_other_balance']){
                    $update_price['user_bo_other_balance'] = $order['user_bo_other_balance'] - $cha2;
                }else{
                    $update_price['user_bo_other_balance'] = 0;
//                    return json(['status' => 0, 'msg' => '可用积分不足']);
                }
            }
        }
        $update_price['user_bo_balance'] = $order['user_bo_balance'] - $order['order_total_price'];

        return $update_price;
    }
}